const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const index = require('./routes/index')
const users = require('./routes/users')
const cart = require('./routes/cart')
const jwtKoa = require('koa-jwt')

const { JWT_SECRET_KEY } = require('./conf/secretKeys')
const { ErrorModel } = require('./model/ResModel')
const { loginCheckFailInfo } = require('./model/ErrorInfo')
const cors = require('koa2-cors')
// 设置允许跨域
// app.use(async (ctx, next)=> {
//   console.log('设置允许跨域')
//   ctx.set("Access-Control-Allow-Origin", "*");
//   await next();
// })
app.use(cors())

// 处理拦截失败
app.use(function(ctx, next){
  return next().catch((err) => {
    if (401 == err.status) {
      ctx.status = 200;
      ctx.body = new ErrorModel(loginCheckFailInfo)
    } else {
      ctx.body = {
        code: 25000,
        message: '系统错误'
      }
    }
  });
});
app.use(jwtKoa({
  secret: JWT_SECRET_KEY //秘匙，一般定义为常量了
}).unless({
  path: [/^\/users\/login/,/^\/users\/register/] // 定义要忽略的文件儿目录
}))

// error handler
// onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(cart.routes(), cart.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.log('捕捉到错误',ctx)
  ctx.body = {
    code: 25000,
    message: '系统错误'
  }

  return 
});

module.exports = app
